
#include "boost/filesystem.hpp"
#include "SyncFileModule.h"
#include "SyncFile.h"
#include "../client-protocol/RequestGet.h"
#include "../port/convert.h"

namespace Client {
namespace File {

class CActionGetFileList : public CRequestAction {

public :

	virtual void DoRequest(CRequest& request, CResponse& response) {

		int oldver = request.GetParameterInt(string("oldver"));
		string& devices = request.GetParameter(string("devices"));

		TableRef tf;
		
		if(devices == "all") tf = CSyncFile::Query();
		else tf = CSyncFile::QueryAfter(oldver);

		if(!tf || tf->GetCount() == 0) {
			response.SetStatus(RESPONSE_STATUS_OK);
			if(tf) tf->Close();
			return;
		}

		TableRef ts = CSyncFile::GetSerializedTable(*tf);
		tf->Close();

		string js = ts->ToString();
		ts->Close();
		
		response.SetStatus(RESPONSE_STATUS_OK);
		response.SetContent(js, string(PACKAGE_CONTENT_TYPE_JSON));
	}
};

class CActionGetFile : public CRequestAction {

public :

	virtual void DoRequest(CRequest& request, CResponse& response) {
		string& id = request.GetParameter(string("id"));
		if(id.length() == 0) {
			response.SetStatus(RESPONSE_STATUS_BadRequest);
			return;
		}

		SyncFileRef sf = CSyncFile::QueryById(id);
		if(!sf || sf->mStatus != FILE_STATUS_NORMAL || sf->mType != FILE_TYPE_FILE) {
			response.SetStatus(RESPONSE_STATUS_FileNotFound);
			return;
		}

		string file_path;
		Util::CConverter::UTF8_TO_Ascii(sf->mStorePath, file_path);

		boost::filesystem::path file = file_path;
		if(!boost::filesystem::exists(file) || !boost::filesystem::is_regular_file(file)) {
			response.SetStatus(RESPONSE_STATUS_FileNotFound);
			return;
		}
		
		response.SetStatus(RESPONSE_STATUS_OK);
		response.SetContentFile(file_path, string(PACKAGE_CONTENT_TYPE_RAW));

		sf->mSyncCount++;
		CSyncFile::UpdateSyncFile(sf);
	}
};

static CActionGetFileList sActionGetFileList;
static CActionGetFile sActionGetFile;

void CSyncFileModule::InitGetAction()
{
	CRequestGet::RegisterAction(string("filelist"), &sActionGetFileList);
	CRequestGet::RegisterAction(string("file"), &sActionGetFile);
}

} // Client
} // File